# -*- coding: utf-8 -*-

__author__ = """WebLion <support@weblion.psu.edu>"""
__docformat__ = 'plaintext'

from AccessControl import ClassSecurityInfo
from Products.Archetypes.atapi import *
from Products.ATReferenceBrowserWidget.ATReferenceBrowserWidget import ReferenceBrowserWidget
from Products.Relations.field import RelationField
from Products.ContactsDirectory.config import *
from Products.ContactsDirectory.PersonGrouping import PersonGrouping
from Products.CMFCore.permissions import View
from Products.CMFCore.utils import getToolByName

from Products.ContactsDirectory.interfaces.group import IGroup
from Products.ContactsDirectory.permissions import ASSIGN_SPECIALTIES_TO_PEOPLE

from zope.interface import implements

schema = Schema((

    RelationField(
        name='people',
        widget=ReferenceBrowserWidget(
            label=u'People',
            label_msgid='ContactsDirectory_label_people',
            i18n_domain='ContactsDirectory',
            base_query={'portal_type':'CDPerson', 'sort_on':'getSortableName'},
            allow_browse=0,
            allow_search=1,
            show_results_without_query=1,      
        ),
        write_permission=ASSIGN_SPECIALTIES_TO_PEOPLE,
        allowed_types=('CDPerson',),
        multiValued=True,
        relationship='GroupInformation'  # weird relationship name is ArchGenXML's fault
    ),
),
)

Group_schema = getattr(PersonGrouping, 'schema', Schema(())).copy() + schema.copy()

class Group(PersonGrouping):
    """
    """
    security = ClassSecurityInfo()
    __implements__ = (getattr(PersonGrouping,'__implements__',()),)
    implements(IGroup)
    meta_type = portal_type = 'CDGroup'

    _at_rename_after_creation = True
    schema = Group_schema
    # Methods
    security.declareProtected(View, 'getGroupInformation')
    def getGroupInformation(self, person):
        """
        Get the group information for a specific person
        """
        refCatalog = getToolByName(self, 'reference_catalog')
        refs = refCatalog.getReferences(self, 'GroupInformation', person)

        if refs:
            return refs[0].getContentObject()
        else:
            return None
    
    #
    security.declarePublic(View, 'getEmails')
    def getEmails(self):
        """
        Get the group emails.
        """
        return [p.getEmail() for p in self.getPeople() if p.getEmail()]

    

registerType(Group, PROJECTNAME)
